package com.jmx.mstcodesandbox.javasandbox;

import com.jmx.mstcodesandbox.CodeSandBox;
import com.jmx.mstcodesandbox.model.ExecuteCodeRequest;
import com.jmx.mstcodesandbox.model.ExecuteCodeResponse;
import com.jmx.mstcodesandbox.model.ProcessInfo;
import com.jmx.mstcodesandbox.utils.ProcessUtil;
import org.springframework.stereotype.Component;

import java.util.*;

@Component("native")
public class JavaNativeCodeSandBox extends JavaAbstractCodeSandBoxTemplate implements CodeSandBox {
    private static final String SECURITY_CLASS_PATH;

    static {
        String fullPath = Objects.requireNonNull(JavaNativeCodeSandBox.class.getClassLoader().getResource("com/jmx/mstcodesandbox/security/")).getPath();
        SECURITY_CLASS_PATH = fullPath.substring(0, fullPath.lastIndexOf("com/jmx/mstcodesandbox/security/"));
    }

    @Override
    public ProcessInfo execute(String inputArgs, String userCodeDir) {
        String runCmdNoArgs = String.format("java -Dfile.encoding=UTF-8 -Xmx256m -cp %s;%s -Djava.security.manager=com.jmx.mstcodesandbox.security.MySecurityManager %s ", userCodeDir, SECURITY_CLASS_PATH, USER_CODE_CLASS_NAME);
        // 运行代码携带参数
        String runCmdWithArgs = runCmdNoArgs + inputArgs;
        return ProcessUtil.executeCmd(runCmdWithArgs);
}

    public static void main(String[] args) {
        // 测试上述方法是否能够正常使用
        // 1.构建参数对象
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputs(Arrays.asList("1 2 3", "3 4 4", "5 6 4"));
        String code = "public class Main{ public static void main(String[] args) {\n" +
                "        int a1 = Integer.parseInt(args[0]);\n" +
                "        int a2 = Integer.parseInt(args[1]);\n" +
                "        int a3 = Integer.parseInt(args[2]);\n" +
                "        System.out.print(a1+a2+a3);\n" +
                "    }}";
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        JavaNativeCodeSandBox javaNativeCodeSandBox = new JavaNativeCodeSandBox();
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandBox.executeCode(executeCodeRequest);
        System.out.println("executeCodeResponse = " + executeCodeResponse);
    }
}
